import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户类型枚举
export enum UserType {
  ADMIN = 'admin',
  REGULAR = 'regular'
}

// 用户接口
export interface User {
  id: string
  username: string
  password: string
  type: UserType
  name?: string
  email?: string
  avatar?: string
  createdAt: Date
}

// 默认管理员账号
const defaultAdmin: User = {
  id: 'admin-1',
  username: 'admin',
  password: 'admin123',
  type: UserType.ADMIN,
  name: '系统管理员',
  avatar: '/src/assets/avatars/admin-avatar.svg',
  createdAt: new Date()
}

export const useUserStore = defineStore('NaturalUser', () => {
  // 当前登录用户
  const currentUser = ref<User | null>(null)

  // 所有用户列表
  const users = ref<User[]>([defaultAdmin])

  // 是否已登录
  const isLoggedIn = computed(() => !!currentUser.value)

  // 用户类型
  const userType = computed(() => currentUser.value?.type || null)

  // 是否是管理员
  const isAdmin = computed(() => userType.value === UserType.ADMIN)



  // 是否是普通用户
  const isRegular = computed(() => userType.value === UserType.REGULAR)

  // 登录方法
  const login = (username: string, password: string): boolean => {
    const user = users.value.find(
      u => u.username === username && u.password === password
    )

    if (user) {
      currentUser.value = user
      return true
    }

    return false
  }

  // 注册方法
  const register = (
    username: string,
    password: string,
    type: UserType.REGULAR,
    name?: string,
    email?: string
  ): boolean => {
    // 检查用户名是否已存在
    if (users.value.some(u => u.username === username)) {
      return false
    }

    // 创建新用户
    const newUser: User = {
      id: `user-${Date.now()}`,
      username,
      password,
      type,
      name,
      email,
      createdAt: new Date()
    }

    // 添加到用户列表
    users.value.push(newUser)

    // 自动登录
    currentUser.value = newUser

    return true
  }

  // 登出方法
  const logout = () => {
    currentUser.value = null
  }

  return {
    currentUser,
    users,
    isLoggedIn,
    userType,
    isAdmin,
    isRegular,
    login,
    register,
    logout
  }
}, {
  persist: {
    // 持久化存储
    storage: localStorage,
    paths: ['currentUser', 'users']
  }
})
